/**
 * @description 微博 view 路由
 * @author 刘煎蛋
 */

const router = require('koa-router')();
const { loginRedirect } = require('../../middlewares/loginChecks');
const { getHomeBlogList } = require('../../controller/blog-home');
const { getFans, getFollowers } = require('../../controller/user-relation');
const { getAtMeCount } = require('../../controller/blog-at');
const { isExists } = require('date-fns');

router.get('/main', loginRedirect, async ( ctx, next ) => {
    const userInfo = ctx.session.userInfo;
    const { id: userId } = userInfo;

    // 获取第一页数据
    const result = await getHomeBlogList( userId );
    const { isEmpty, blogList, pageSize, pageIndex, count } = result.data;

    // 获取粉丝
    const fansResult = await getFans( userId );
    const { count: fansCount, fansList } = fansResult.data;

    // 获取关注人列表
    const followersResult = await getFollowers( userId );
    const { count: followersCount, follwersList  } = followersResult.data;

    // 获取 @ 结果
    const atCountResult = await getAtMeCount( userId );
    const { count: atCount } = atCountResult.data;

    await ctx.render('index',{
        userData: {
            userInfo,
            fansData: {
                count: fansCount,
                list: fansList
            },
            followersData: {
                count: followersCount,
                list: follwersList
            },
            atCount
        },
        blogData: {
            isEmpty,
            blogList,
            pageSize,
            pageIndex,
            count
        }
    })
})

router.get('/profile', loginRedirect, async ( ctx, next ) => {
    const { userName } = ctx.session.userInfo;
    ctx.redirect(`/profile/${userName}`)
})

router.get('/profile/:userName', loginRedirect, async ( ctx, next ) => {

    const myUserInfo = ctx.session.userInfo;
    const myUserName = myUserInfo.userName;

    let curUserInfo;
    const { userName: curUserName } = ctx.params;
    const isMe = myUserName === curUserName;

    // 是当前登录用户
    if ( isMe ) {
        curUserInfo = myUserInfo
    } else {
        // 不是当前登录用户
        const existResult = await isExist( curUserName );
        if ( existResult.errno !== 0 ) {
            return;
        }
        curUserInfo = existResult.data;
    }

    // 获取微博第一页数据
    const result = await getProfileBlogList( curUserName, 0 );
    const { isEmpty, blogList, pageSize, pageIndex, count } = result.data;

    // 获取粉丝
    const fansResult = await getFans(curUserInfo.id);
    const { count: fansCount, fansList } = fansResult.data;

    // 获取关注人列表
    const followersResult = await getFollowers( curUserInfo.id );
    const { count: followersCount, followersList } = followersResult.data;

    // 我是否关注了此人
    const amIFollowed = fansList.some( item => {
        return item.userName === myUserName
    })

    // 获取@数量
    

})


module.exports = router
